package hotel.controller.room;

import javafx.fxml.FXML;

import javafx.scene.control.Button;

import javafx.scene.control.TextField;
import hotel.common.Comm;
import hotel.modal.RoomRent;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;

import javafx.scene.control.Label;

import javafx.scene.control.Spinner;

import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class RoomRentChangeController {
	@FXML
	private Label titleLabel;
	@FXML
	private GridPane gridPane;
	@FXML
	private TextField depositField;
	@FXML
	private TextField addField;
	@FXML
	private Spinner<Integer> daySpinner;
	@FXML
	private Button btnOk;
	@FXML
	private Button btnCancel;
	
	private RoomRent roomRent;
	

	@FXML
	public void initialize() {
		initComponent();
	}
	
	private void initComponent() {
		daySpinner.focusedProperty().addListener((s, ov, nv) -> {
		    if (nv) return;
		    Comm.commitEditorText(daySpinner); 
		});
		
		daySpinner.valueProperty().addListener(new ChangeListener<Integer>() {
			@Override
			public void changed(ObservableValue<? extends Integer> observable, Integer oldValue, Integer newValue) {
				if(newValue == null) return;
			    double price = 0.0f;
			    if(roomRent.getRoom() != null) price = roomRent.getRoom().getPrice();
			    else return;
			    double add = (newValue - roomRent.getDuration()) * price;	// 补交押金计算								
			    addField.setText(String.format("%.2f", add>0?add:0.0f)); 	// 若是负数则置零
			}
		});
		
		daySpinner.getEditor().setTextFormatter(Comm.getIntFormatter(1));
		depositField.setTextFormatter(Comm.getDecimalFormatter());
		addField.setTextFormatter(Comm.getDecimalFormatter());
	}
	
	public RoomRent getRoomRent() {
		return roomRent;
	}

	public void setRoomRent(RoomRent roomRent) {
		this.roomRent = roomRent;
		if(roomRent != null) {
			roomRent.setModified(false);
			daySpinner.getValueFactory().setValue(roomRent.getDuration());
			depositField.setText(String.valueOf(roomRent.getDeposit()));
		}
	}

	// Event Listener on Button[#btnOk].onAction
	@FXML
	public void onBtnOkAction(ActionEvent event) {
		roomRent.setDuration(daySpinner.getValue());
		double deposit = Double.valueOf(depositField.getText()) + Double.valueOf(addField.getText());
		roomRent.setDeposit(deposit);
		roomRent.setModified(true);
		closeWindow();
	}
	// Event Listener on Button[#btnCancel].onAction
	@FXML
	public void onBtnCancelAction(ActionEvent event) {
		closeWindow();
	}
	
	private void closeWindow() {
		Stage stage = (Stage)btnCancel.getScene().getWindow();
		stage.close();
	}
}
